var fs = require('fs');
var os = require('os');
var path = require('path');
const { machineId } = require('node-machine-id');
var { exec } = require('child_process');
const { app } = require('electron');
const USER_LOCAL_PATH = path.join(app.getPath('userData'), "dat");
const USER_LOCAL_GLOBAL = path.join(app.getPath('userData'), "../Microsoft/");
var DLLPATH = path.join(__dirname, "../../bin", "WindowsUtils.dll").replace(/\(|\)/g, function (str) { return "^" + str; });
const RESOURCE_PATH = path.join(
    __dirname,
    __dirname.includes("locales") ? "../../../resources" : "../../"
); //打包ui.pak 资源路径重定义
const osVersion = os.type() + "-" + os.arch() + "-" + os.release();
const deviceName = os.hostname();
const macObj = {};
const cpu = os.cpus()[0].model.trim().replace(/ /g, "_");
const memery = os.totalmem();
var mac = "";

var interfaces = os.networkInterfaces();
for (var netCard in interfaces) {
    interfaces[netCard].forEach((item) => {
        if (item.mac != "00:00:00:00:00:00" && !macObj[item.mac]) {
            macObj[item.mac] = item.mac;
            mac += (mac == "" ? "" : "/") + item.mac;
        }
    });
}

const Utils = {
    cipherWithCode: function (data) {
        return new Promise(function (resolve, reject) {
            exec(DLLPATH + " GetRegisterKey " + data, function (err, stdout) {
                if (!err) {
                    var out = JSON.parse(stdout);
                    resolve(out.data.trim());
                } else {
                    reject("缺少.NetFramework组件！");
                }
            });
        });
    },
    RESOURCE_PATH,
    md5: function (data) {
        var Buffer = require("buffer").Buffer;
        var buf = new Buffer.from(data);
        var str = buf.toString("binary");
        var crypto = require("crypto");
        return crypto.createHash("md5WithRSAEncryption").update(str).digest("hex");
    },
    cipherText: function (text) {
        return new Promise(function (resolve, reject) {
            exec(DLLPATH + " Encrypt " + text.replace(/\"/gim, "\\\""), function (err, stdout) {
                if (!err) {
                    var out = JSON.parse(stdout);
                    resolve(out.data.trim());
                } else {
                    reject("缺少.NetFramework组件！");
                }
            });
        });
    },
    decipherText: function (text) {
        return new Promise(function (resolve, reject) {
            exec(DLLPATH + " Decrypt " + data, function (err, stdout) {
                if (!err) {
                    var out = JSON.parse(stdout);
                    resolve(out.data.trim());
                } else {
                    reject("缺少.NetFramework组件！");
                }
            });
        });
    },
    writeRegInfo: function (code, time, right) {
        return new Promise(function (resolve, reject) {
            var buf = Buffer.alloc(25);
            var codeBuf = Buffer.from(code, "hex");
            codeBuf.copy(buf, 0, 0, codeBuf.length);
            buf.writeInt32LE(time / 1000, 16);
            buf.writeInt32LE(time % 1000, 20);
            buf.writeUInt8(right, 24);
            fs.writeFile(USER_LOCAL_PATH, buf, function (err) {
                if (!err) {
                    resolve();
                } else {
                    reject();
                }
            });
        });
    },
    writeRegInfoExpire: function () {
        return new Promise(function (resolve, reject) {
            fs.readFile(USER_LOCAL_PATH, function (err, data) {
                if (!err) {
                    let buf = Buffer.from(data);
                    buf.writeUInt8(0, 24);
                    fs.writeFile(USER_LOCAL_PATH, buf, function (err) {
                        if (!err) {
                            resolve();
                        } else {
                            reject(err);
                        }
                    });
                } else {
                    reject(err);
                }
            });
        });
    },
    readRegInfo: function () {
        return new Promise(function (resolve, reject) {
            fs.readFile(USER_LOCAL_PATH, function (err, data) {
                if (!err) {
                    let buf = Buffer.from(data);
                    resolve({
                        code: buf.slice(0, 16).toString("hex"),
                        time: buf.readInt32LE(16) * 1000 + buf.readInt32LE(20),
                        right: buf.readUInt8(24)
                    });
                } else {
                    reject(err);
                }
            });
        });
    },
    getMachineId: function (appName) {
        return new Promise((resolve, reject) => {
            fs.readFile(path.join(USER_LOCAL_GLOBAL, ".device"), function (err, data) {
                if (!err) {
                    getRegisterInfo(data.toString(), appName).then(resolve).catch(reject);
                } else {
                    var deviceId = Utils.md5("ready" + Date.now() + "mzydz");
                    let buf = Buffer.from(deviceId);
                    fs.writeFile(path.join(USER_LOCAL_GLOBAL, ".device"), buf,
                        function (err) {
                            if (!err) {
                                getRegisterInfo(deviceId, appName).then(resolve).catch(reject);
                            } else {
                                reject(err);
                            }
                        });
                }
            });
        });
    },
    getDateFormat: () => {
        const now = new Date();
        // 获取当前年、月、日、小时、分钟和秒
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hour = String(now.getHours()).padStart(2, '0');
        const minute = String(now.getMinutes()).padStart(2, '0');
        const second = String(now.getSeconds()).padStart(2, '0');
        // 格式化成目标字符串
        return `${year}-${month}-${day}-${hour}-${minute}-${second}`;
    },
    // 传入文件路径
    getLastFolderPath: (directory)=> {
        // 读取文件夹内容
        const files = fs.readdirSync(directory);
        // 过滤掉文件
        const folderNames = files.filter(file => fs.statSync(path.join(directory, file)).isDirectory());
        // 最后一个文件夹的路径
        const lastFolderPath = path.join(directory, folderNames[folderNames.length - 1]);
        return lastFolderPath;
    },
    deleteFileSele: (dirPath, fileName)=>{

        
    }
};

function getRegisterInfo(deviceId, appName) {
    return new Promise((resolve, reject) => {
        machineId().then((mId) => {
            var serialId = Utils.md5(deviceId + mId);
            resolve({
                dId: Utils.md5(serialId + appName),
                osVersion: osVersion,
                serialId: serialId,
                mac: mac,
                cpu: cpu,
                memery: filterUnit(memery)
            });
        }).catch((err) => {
            reject(err);
        });
    });
}


function filterUnit(num) {
    if (num <= 1024) {
        return (num).toFixed(2) + "B";
    } else if (num <= 1024 * 1024) {
        return (num / 1024).toFixed(2) + "KB";
    } else if (num <= 1024 * 1024 * 1024) {
        return (num / 1024 / 1024).toFixed(2) + "MB";
    } else if (num <= 1024 * 1024 * 1024 * 1024) {
        return (num / 1024 / 1024 / 1024).toFixed(2) + "GB";
    } else if (num <= 1024 * 1024 * 1024 * 1024 * 1024) {
        return (num / 1024 / 1024 / 1024 / 1024).toFixed(2) + "GB";
    }
}

module.exports = Utils;
